<script setup>
import { ref, watch,defineEmits,defineProps } from 'vue';
import axios from 'axios'; // 确保你已正确配置 axios
import {userStore} from "@/store/index.js";
import {ElMessage} from "element-plus";
import {useRouter} from "vue-router";

const store = userStore();
const router = useRouter()

// 定义 props
const props = defineProps({
  dialogVisible: Boolean,  // 是否可见
  bookId: Number   // 书籍的 id
});

const dialogVisibleInner = ref(false);  // 内部是否可见的属性
// 监听 props 的变化
watch(() => props.dialogVisible, (newVal) => {
  console.log("newVal",newVal)
  if (newVal) {
    dialogVisibleInner.value = newVal;
    findById();
  }
});

const book = ref({});

const findById = async () => {
  try {
    const resp = await axios.get(`/book/${props.bookId}`);
    book.value = resp.data;
  } catch (e) {
    console.log('查询书籍详情异常', e);
  }
};


const emit = defineEmits(['close']);
const handlerClose = () => {
  dialogVisibleInner.value = false
  // 子传父
  emit('close',false);
};


// 加入购物车
const addCart = (bookId) => {
  // 判断是否登录
  if (!store.loggedIn) {
     ElMessage.error("请先登录，再访问购物车")
     router.push("/login");
     return;
  }
  axios.post(`/cart/${bookId}`).then(res=>{
    ElMessage.success("添加购物车成功")
    handlerClose()
  })
}

</script>


<template>
  <!-- 查看详情对话框，打开对话框调用方法 -->
  <el-dialog v-model="dialogVisibleInner" title="书籍详情" @close="handlerClose">
    <div class="dialog-content">
      <div class="book-image">
        <img :src="$urlImage + book.imgSrc" alt="书籍详情">
      </div>
      <div class="book-info">
        <h2 class="title">《{{ book.name }}》</h2>
        <p class="author">作者：{{ book.author }}</p>
        <p class="publisher">出版社：{{ book.publisher }}</p>
        <p class="price">价格：&yen;{{ book.price }}</p>
        <el-divider></el-divider>
        <p class="intro">{{ book.detail }}</p>
        <div class="button-group">
          <el-button type="warning" size="medium" icon="el-icon-shopping-cart-full" @click="addCart(book.id)">加入购物车</el-button>
          <el-button type="primary" size="medium" @click="handlerClose" icon="el-icon-circle-close">关闭</el-button>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<style scoped>
.dialog-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.book-image {
  width: 30%;
  text-align: center;
}

.book-image img {
  max-width: 100%;
  height: auto;
}

.book-info {
  width: 68%;
}

.title {
  font-size: 24px;
  font-weight: bold;
  margin: 0 0 6px;
}

.author {
  font-size: 18px;
  margin: 0 0 4px;
}

.publisher,
.price {
  font-size: 16px;
  margin: 0 0 2px;
}

.intro {
  font-size: 14px;
  margin: 0 0 10px;
}

.button-group {
  display: flex;
  justify-content: flex-end;
}
</style>
